﻿using System;
using System.Collections.Generic;
using Kiva7.DataClasses;

namespace Kiva7.ViewModels
{
    public class LoanMonthTotalsDictionary : Dictionary<int, LoanMonthTotals>
    {
        private int GetKey(DateTime date)
        {
            DateTime d = date;

            return d.Year * 100 + d.Month;
        }

        private LoanMonthTotals GetItem(DateTime date)
        {
            int key = GetKey(date);

            if (this.ContainsKey(key))
            {
                return this[key];
            }
            else
            {
                LoanMonthTotals t = new LoanMonthTotals();
                t.Year = date.Year;
                t.Month = date.Month;
                Add(key, t);
                return t;
            }
        }

        public new void Clear()
        {
            foreach (var t in this)
            {
                t.Value.Clear();
            }
        }

        public void Add(Loan loan)
        {
            if (loan.PostedDate.HasValue)
            {
                LoanMonthTotals t = GetItem(loan.PostedDate.Value);
                t.Count++;
            }
            if (loan.FundedDate.HasValue)
            {
                LoanMonthTotals t = GetItem(loan.FundedDate.Value);
                t.CountRepaying++;
            }
            if (loan.PaidDate.HasValue)
            {
                LoanMonthTotals t = GetItem(loan.PaidDate.Value);
                t.CountRepaying--;
                t.CountPaid++;
            }
        }
    }
}
